package com.farmer.h5.net;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

import com.farmer.h5.util.TipsToast;

public class HttpUtil
{
    /**
     * 请求返回一个json对象
     * 
     * @param url 路径
     * @param params 参数（json对象）
     * @return 返回值（json对象）
     * @throws ClientProtocolException
     * @throws IOException
     * @throws JSONException
     */
    public static JSONObject getJSONObj(String url, JSONObject params)
        throws ClientProtocolException, IOException, JSONException
    {
        String result = "";
        HttpClient hc = new DefaultHttpClient();
        hc.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
        HttpPost request = new HttpPost(url);
        
        StringEntity entity = null;
        if (params != null && params.length() > 0)
        {
            Log.v("request : ", params.toString());
            entity = new StringEntity(params.toString(), HTTP.UTF_8);
            entity.setContentType("application/json");
            request.setEntity(entity);
        }
        HttpResponse response = hc.execute(request);
        if (response.getStatusLine().getStatusCode() == 200)
        {
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
            Log.v("response : ", result);
            return new JSONObject(result);
        }
        return null;
    }
    
    /**
     * 是否有网络
     * 
     * @param ctx 上下文
     * @return
     */
    public static boolean isNetWork(Context ctx)
    {
        boolean hasNetWork = false;
        ConnectivityManager connManager = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connManager != null)
        {
            NetworkInfo[] infos = connManager.getAllNetworkInfo();
            if (infos != null)
            {
                for (int i = 0; i < infos.length; i++)
                {
                    if (infos[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        hasNetWork = true;
                        break;
                    }
                    else if (infos[i].getState() == NetworkInfo.State.DISCONNECTED || infos[i].getState() == NetworkInfo.State.DISCONNECTING
                        || infos[i].getState() == NetworkInfo.State.UNKNOWN)
                    {
                        hasNetWork = false;
                    }
                }
            }
            else
            {
                hasNetWork = false;
                TipsToast.makeText(ctx, "网络连接失败，请检查网络设置", Toast.LENGTH_SHORT).show();
            }
        }
        else
        {
            hasNetWork = false;
            TipsToast.makeText(ctx, "网络连接失败，请检查网络设置", Toast.LENGTH_SHORT).show();
        }
        return hasNetWork;
    }
    
    /**
     * 获取当前APP的版本号versionName
     * 
     * @param context 上下文
     * @return APP的versionName
     */
    public static String getAppVersion(Context context)
    {
        String versionName = "";
        // 获取当前APP的版本号versionName
        PackageManager packageManager = context.getPackageManager();
        try
        {
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
        }
        catch (NameNotFoundException e)
        {
            e.printStackTrace();
        }
        return versionName;
    }
}
